package Middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"web_back_go/Common"
	"web_back_go/Response"
)

// AuthMiddleware 是一个中间件函数，用于验证 Authorization 头并检查 Redis 中是否存在对应的值，可排除指定路径
func AuthMiddleware(redisClient *redis.Client, excludedPaths ...string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 检查当前路径是否在排除列表中
		for _, path := range excludedPaths {
			if c.Request.URL.Path == path {
				c.Next()
				return
			}
		}

		authHeader := c.GetHeader("Authorization")

		if authHeader == "" {
			c.JSON(401, gin.H{"error": "Authorization header missing"})
			c.Abort()
			return
		}
		_, UserName, _ := Common.CodeToken(authHeader)
		key := "auth:" + UserName
		exists, err := redisClient.Exists(c, key).Result()
		if err != nil {

			c.JSON(200, Response.ResponseBody{
				Code:      "A00004",
				Msg:       "Unauthorized",
				Data:      nil,
				Version:   "v1.0",
				Timestamp: 0,
				Sign:      nil,
				Success:   false,
				Fail:      true,
			})
			c.Abort()
			return
		}
		if exists == 0 {
			c.JSON(200, Response.ResponseBody{
				Code:      "A00004",
				Msg:       "Unauthorized",
				Data:      nil,
				Version:   "v1.0",
				Timestamp: 0,
				Sign:      nil,
				Success:   false,
				Fail:      true,
			})
			c.Abort()
			return
		}

		c.Next()
	}
}
